/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月21日 上午10:14:29 
 * 
 */
package phoenics.upservice.service;

import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Lists;

import phoenics.upservice.dto.ListPage;
import phoenics.upservice.dto.ListTerm;
import phoenics.upservice.entity.Project;
import phoenics.upservice.repository.ProjectRepo2;

/**
 *
 */
//@Service  
public class ProjectServiceBack {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ProjectServiceBack.class);
	
	private Predicate [] takePredicate(Stream<Predicate> s ) {
		return s.filter(p->p!=null).toArray(Predicate[]::new);
	}
	public Specification<Project> query4Miuti(String projectCategory,String projectArea,Long max,Long min,int up){
		final Long mMax=Optional.ofNullable(max).orElse(new Long(0));
		final Long mMin=Optional.ofNullable(min).orElse(new Long(0));
		return (root,query,cb)->{
			//@Query( value = " select p from Project p  where p.projectCategory=?1 and p.projectArea=?2 and p.id<=?3 " )  
			Path<String> projectCategoryPath = root.get("projectCategory");  
			Path<String>projectAreaPath = root.get("projectArea"); 
			Predicate ca=Optional.ofNullable(projectCategory).filter(s->!StringUtils.isEmpty(s)).map(c->cb.equal(projectCategoryPath, c)).orElse(null);
			Predicate ar=Optional.ofNullable(projectArea).filter(s->!StringUtils.isEmpty(s)).map(c->cb.equal(projectAreaPath, c)).orElse(null);
			Predicate max_id=cb.le(root.<Long>get("id"), mMax);
			Predicate min_id=cb.gt(root.<Long>get("id"), mMin);
			if(up!=0) {
				query.where(takePredicate(Stream.of(ca,ar,max_id)));
			}else {
				query.where(takePredicate(Stream.of(ca,ar,min_id)));
			}
			return query.getRestriction();
		};
	}
	public Specification<Project> query4Miuti(ListTerm terms,int up){
		return query4Miuti(terms.getClassifyCode(),terms.getAreaCode(),terms.getMax() ,terms.getMin(),up);
	}
	
	
	
	
}
